define(['moment'], function (moment) {
    return ['$state', '$scope', '$rootScope', '$filter', '$stateParams', 'config', 'MMWService', '$mdDialog', '$timeout','$calculater',
        function ($state, $scope, $rootScope, $filter, $stateParams, config, $MMWService, $mdDialog, $timeout, $calculater) {
            $scope.checkBoxList = {};
            $scope.init = function () {
                $scope.condition = {
                    op_no: '',
                    sub_op_no: '',
                    plot_no: ''
                };
                $scope.rollbackInfo = {
                    op_no: '',
                    sub_op_no: '',
                    employee_work_detail: []
                };

                $scope.isSelectAll = false;
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            $scope.favorite = function(callback){
                if(config.setting.OperatingArea==''){
                    $scope.$root.showAlert($filter('translate')('home.showAlert'));
                    return;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: 38,
                    mode:'M',
                    key:'page_no',
                    header : [
                        {label: $filter('translate')('common.queryList.op_c'), code:'page_no'},
                        {label: $filter('translate')('common.queryList.op_n'), code:'page_name'}
                    ],
                    selectKey:{key:'favourite', true:'1', false:'0'},
                    setCondition:function(conditions){
                        conditions.push({column_name:'MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                        return conditions;
                    },
                    confirm: function(selectItem, dialog){
                        var content = {
                            master_type: 6, //6.子作業工作平台,
                            master_no: config.setting.OperatingArea,
                            favourite_sub_op_detail:[]
                        };
                        if(selectItem && selectItem.length > 0){
                            selectItem.forEach(function(item){
                                if(item.favourite == '1'){

                                    content.favourite_sub_op_detail.push({
                                        op_no: item.page_no,
                                        op_name: item.page_name
                                    });
                                }
                            });
                        }
                        beforeSaveFavorite(content.favourite_sub_op_detail, function(){
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                content : content,
                                success : function(data){
                                    dialog.hide();
                                    if(callback)
                                        callback();
                                }
                            });
                        });
                    }
                });
            };

            $scope.isEnableConfrim = function(){
                var enable = false;
                for(var i = 0; i < $scope.rollbackInfo.employee_work_detail.length; i++){
                    if($scope.rollbackInfo.employee_work_detail[i].isSelect){
                        enable = true;
                        break;
                    }
                }
                return enable;
            };

            // 確認取消
            $scope.confirm = function () {
                beforeConfirm(function(){
                    var content = {
                        op_no: $scope.rollbackInfo.op_no,
                        sub_op_no: $scope.rollbackInfo.sub_op_no,
                        employee_work_detail: []
                    };
                    content.employee_work_detail = $filter('filter')($scope.rollbackInfo.employee_work_detail, {isSelect: true}, true);
                    rollbackWorkSetProcess(content, function(){
                        $scope.search();
                    });
                });
            };

            //查詢 - 作業站開窗
            $scope.loadOpNoList = function () {
                $scope.$root.showQueryList({
                    pageRecord: 25,
                    header: [
                        {label:$filter('translate')('common.queryList.op_c'), code:'page_no'},
                        {label:$filter('translate')('common.queryList.op_n'), code:'page_name'}
                    ],
                    query: function(conditions, feedback){
                        $MMWService.pageNumberInfoGet(
                            {
                                page_mode: 38,
                                query_condition_info:[
                                    {column_name:'MASTERNO', query_mode:'0', value: config.setting.OperatingArea, merge_condition_model:'AND' }
                                ]
                            },function(data){
                                var temp = $filter('filter')(data, {favourite:'1'});
                                //var temp = data.page_number_info_get;
                                if(temp && temp.length){
                                    feedback(temp);
                                } else {
                                    $scope.$root.showConfirm($filter('translate')('G0201.msg.favorite_empty'), function(confirmDialog){
                                        confirmDialog.hide();
                                        $timeout(function(){
                                            $scope.favorite(function(){
                                                $scope.loadOpNoList();
                                            });
                                        }, 200);
                                    });
                                }
                            }
                        );
                    },
                    selectCode: $scope.condition.op_no||'',
                    confirm : function(selectItem, dialog){
                        $scope.condition.op_no = selectItem.page_no;
                        $scope.condition.op_name = selectItem.page_name;
                        //清空子作業
                        $scope.condition.sub_op_no = '';
                        $scope.condition.sub_op_name = '';
                        //清空生產批
                        $scope.condition.plot_no = '';
                        dialog.hide();
                    }
                });
            };

            //查詢 - 子作業開窗
            $scope.loadSubOpNoList = function () {
                if($scope.condition.op_no != ''){
                    $scope.$root.showQueryList({
                        header: [
                            {label:$filter('translate')('G0201.queryList.sub_op_no'), code:'page_no'},
                            {label:$filter('translate')('G0201.queryList.sub_op_name'), code:'page_name'}
                        ],
                        query: function(conditions, feedback){
                            $MMWService.pageNumberInfoGet(
                                {
                                    page_mode: 39,
                                    query_condition_info:[
                                        {column_name:'A.OPNO', query_mode:'0', value: $scope.condition.op_no, merge_condition_model:'AND' }
                                    ]
                                },function(data){
                                    feedback(data);
                                }
                            );
                        },
                        selectCode: $scope.condition.sub_op_no||'',
                        confirm : function(selectItem, dialog){
                            $scope.condition.sub_op_no = selectItem.page_no;
                            $scope.condition.sub_op_name = selectItem.page_name;                            
                            dialog.hide();
                        }
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('G0201.msg.op_no_empty'));
                }
            };

            //查詢 - 生產批複合開窗
            $scope.loadPlotNoList = function () {
                if ($scope.condition.op_no != '') {
                    $MMWService.showQueryListPNIG({
                        page_mode: '36-2',
                        condition: [
                            {name:$filter('translate')('common.queryList.plot_no'), column_name:'lb.BaseLotNo', query_mode:'2', value: $scope.condition.plot_no}
                        ],
                        pageRecord: 25,
                        header: [
                            {label:$filter('translate')('common.queryList.plot_no'), code:'page_no'},
                            {label:$filter('translate')('G0201.queryList.cur_qty'), code:'cur_qty'}
                        ],
                        selectCode: $scope.condition.plot_no,
                        setCondition:function(conditions){
                            conditions.push({column_name:'OPNo', query_mode:'2', value:$scope.condition.op_no });
                            return conditions;
                        },
                        confirm : function(selectItem){
                            $scope.condition.plot_no = selectItem.page_no;
                        }
                    });
                }
                else {
                    $scope.$root.showAlert($filter('translate')('G0201.msg.op_no_empty'));
                }
            };

            //全選
            $scope.selectAll = function () {
                $scope.isSelectAll = !$scope.isSelectAll;
                $scope.rollbackInfo.employee_work_detail.forEach(function(item){
                    item.isSelect = $scope.isSelectAll;
                });
            };

            $scope.itemCheck = function (index, item) {
                item.isSelect = !item.isSelect;
            };

            $scope.search = function(){
                beforeSearch(function(){
                    $scope.isSelectAll = false;
                    $scope.rollbackInfo.employee_work_detail = [];
                    rollbackWorkSetInfoGet($scope.condition, function(data){
                        if(data.length > 0){
                            $scope.rollbackInfo = {
                                op_no: $scope.condition.op_no,
                                sub_op_no: $scope.condition.sub_op_no,
                                employee_work_detail: data
                            };
                        } else {
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        }
                    });
                });
            };

            var element_plot_no;
            //20170511 modify by Dustdusk for 新增barcode/QRcode輸入功能
            $scope.focusInputPlot = function(){
                element_plot_no = document.getElementById('input_plot');
                element_plot_no.focus();
            };

            //barcode輸入
            $scope.input_plot_no = function(event){
                if(event.keyCode == 13){
                    element_plot_no.blur();
                    input_plot_no_callback();
                } else {
                    $scope.barcode_plot_no = $scope.barcode_plot_no||'';
                    if(event.key){
                        $scope.barcode_plot_no += event.key;
                    } else {
                        $scope.barcode_plot_no += String.fromCharCode(event.keyCode);
                    }
                }
            };

            //QRCode輸入
            $scope.qrcode_plot_no = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        $scope.barcode_plot_no = result.text;
                        input_plot_no_callback();
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'landscape'
                });
            };

            function input_plot_no_callback(){
                //檢查輸入的對不對
                var barcode_plot_no = $scope.barcode_plot_no;
                var temp_plot_array = barcode_plot_no.split(';');
                $scope.barcode_plot_no = '';
                if(temp_plot_array.length == 3){
                    $scope.condition.plot_no = temp_plot_array[0] || '';
                    $scope.condition.op_no = temp_plot_array[1] || '';
                    $scope.condition.sub_op_no = temp_plot_array[2] || '';
                    $scope.condition.platform_type = '1';
                    subOpParametersCheckProcess($scope.condition, function(){
                        $scope.search();
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('G0201.msg.barcode_format_error'), function(){
                        element_plot_no.focus();
                    });
                }
            }

            function beforeSearch(callback){
                var msg = '';

                if($scope.condition.op_no == ''){
                    msg = $filter('translate')('G0201.msg.op_no_empty');
                } else if($scope.condition.sub_op_no == ''){
                    msg = $filter('translate')('G0201.msg.sub_op_no_empty');
                }

                if(msg == ''){
                    if (callback)
                        callback();
                } else {
                    $scope.$root.showAlert(msg);
                }
            }

            function beforeConfirm(callback){
                var msg = '';
                if(msg == ''){
                    if (callback)
                        callback();
                } else {
                    $scope.$root.showAlert(msg);
                }
            }

            function beforeSaveFavorite(favoriteList, callback){
                var isDeleteCurrentOp = false;
                if($scope.condition.op_no && $scope.condition.op_no != ''){
                    if(favoriteList && favoriteList.length > 0){
                        var filterList = $filter('filter')(favoriteList, {op_no: $scope.condition.op_no}, true);
                        if(filterList.length == 0){
                            isDeleteCurrentOp = true; //使用者將"目前的作業站"從我的最愛移除了
                        }
                    }
                }

                if(isDeleteCurrentOp){
                    $scope.$root.showAlert($filter('translate')('G0201.msg.favorite_remove'));
                    $scope.condition.op_no = '';
                    $scope.condition.op_name = '';
                    $scope.condition.sub_op_no = '';
                    $scope.condition.plot_no = '';
                    $scope.rollbackInfo.op_no = '';
                    $scope.rollbackInfo.sub_op_no = '';
                    $scope.rollbackInfo.employee_work_detail = [];
                }
                if(callback)
                    callback();

            }

            //取得取消上下工資訊
            function rollbackWorkSetInfoGet(content, callback) {
                var query_condition_info = [];
                if($scope.condition.op_no!=undefined && $scope.condition.op_no!='')
                    query_condition_info.push({column_name:'A.OPNO', query_mode:'0', value:$scope.condition.op_no, merge_condition_model:'AND' });
                if($scope.condition.sub_op_no!=undefined && $scope.condition.sub_op_no!='')
                    query_condition_info.push({column_name:'A.SUBOPNO', query_mode:'0', value:$scope.condition.sub_op_no, merge_condition_model:'AND' });
                if($scope.condition.plot_no!=undefined && $scope.condition.plot_no!='')
                    query_condition_info.push({column_name:'A.LOGINPLACENO', query_mode:'0', value:$scope.condition.plot_no, merge_condition_model:'AND' });

                $MMWService.pageNumberInfoGet({
                    page_mode: 'rollback_work_set_info_get',
                    query_condition_info:query_condition_info
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            }

            //子作業參數檢查
            function subOpParametersCheckProcess(content, callback){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.sub_op_parameters_check_process',
                    content: content,
                    success: function (data) {
                        if (callback)
                            callback();
                    }
                });
            }

            //完成送出
            function rollbackWorkSetProcess(content, callback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.rollback_work_set_process',
                    content: content,
                    success: function (data, response) {
                        $scope.$root.showToast(response.Message);
                        if (callback)
                            callback();
                    }
                });
            }
        }
    ];
});
